function StaminaDrainStart (P, key)
	if((key==IN_SPEED || P:KeyDown(IN_SPEED))) then
		timer.Create("StaminaDrain",0.2,0, function()			
			P:SetNWInt("Stamina",P:GetNWInt("Stamina")-1)
			local mag= math.sqrt(P:GetVelocity().x*P:GetVelocity().x+P:GetVelocity().y*P:GetVelocity().y+P:GetVelocity().z*P:GetVelocity().z)
			if(mag<1) then timer.Destroy("StaminaDrain") timer.Simple(3,function() StaminaRestore(P) end) return end
			if(P:GetNWInt("Stamina")<0) then 
				RagdollTrip(P)
				timer.Destroy("StaminaDrain")
			end
		end)
	end	
	local mag= math.sqrt(P:GetVelocity().x*P:GetVelocity().x+P:GetVelocity().y*P:GetVelocity().y+P:GetVelocity().z*P:GetVelocity().z)
	if(mag<3) then
		timer.Simple(3,function() StaminaRestore(P) end)
	end
	
end
   
hook.Add( "KeyPress", "SDrain", StaminaDrainStart ) 

function StaminaDrainEnd (P, key)
	if(key==IN_SPEED && !P:KeyDown(IN_SPEED)) then
		timer.Destroy("StaminaDrain")
	end
	
	local mag= math.sqrt(P:GetVelocity().x*P:GetVelocity().x+P:GetVelocity().y*P:GetVelocity().y+P:GetVelocity().z*P:GetVelocity().z)
	if(mag<3) then
		
	end
end
   
hook.Add( "KeyRelease", "SDrain", StaminaDrainEnd ) 


function StaminaRestore (P)
	timer.Create("StaminaRestore",0.5,0,function()
		if(P:GetNWInt("Stamina")<100) then
			P:SetNWInt("Stamina",P:GetNWInt("Stamina")+1)
		end
		local mag= math.sqrt(P:GetVelocity().x*P:GetVelocity().x+P:GetVelocity().y*P:GetVelocity().y+P:GetVelocity().z*P:GetVelocity().z)
		if(mag>3) then timer.Destroy("StaminaRestore") end
	end)
end

function RagdollTrip(ply)
	if ply:Alive() then
		local velocity=ply:GetVelocity()
		ply:Freeze(true)
		ply:DrawWorldModel(false)
		ply:DrawViewModel(false)
		ply:SetNoTarget(true)
		ply:SetParent(RagDoll)
		local RagDoll = ents.Create("prop_ragdoll")
		RagDoll:SetModel(ply:GetModel())
		RagDoll:SetName(ply:GetName())
		RagDoll:SetColor(ply:GetColor())
		RagDoll:SetMaterial(ply:GetMaterial())
		RagDoll:SetPos(ply:GetPos())
		RagDoll:SetAngles(ply:GetAngles())
		RagDoll:SetHealth(ply:Health())
		RagDoll:SetOwner(ply)
		RagDoll:Spawn()
		RagDoll:Activate()
		RagDoll:GetPhysicsObject():SetVelocity(velocity*10)
		ply:Spectate( OBS_MODE_CHASE )
		ply:SpectateEntity( RagDoll )

		timer.Simple(3, function() Unrag(ply, RagDoll) end)
	end
end

function Unrag(ply, RagDoll) -- hmm, what happens if the ragdoll's health drops to/below 0? might want to take a look later.
	local health = RagDoll:Health()
	local hunger = ply:GetNWInt("Hunger")

	ply:SetDSP( 4, false)
	ply:Spectate(0)
	ply:SpectateEntity()
	ply:UnSpectate( RagDoll )
	ply:Spawn()
	ply:SetPos(RagDoll:GetPos())
	RagDoll:Remove()
	ply:DrawWorldModel(true)
	ply:DrawViewModel(true)
	ply:SetNoTarget(false)
	ply:Freeze(false)
	ply:SetHealth(health) 
	ply:SetNWInt("Stamina", 10)
	ply:SetNWInt("Hunger", hunger)
end

